//
//  MainViewController.m
//  svqj
//
//  Created by xftt on 14-6-20.
//
//

#import "MainViewController.h"
#import "MenuViewController.h"
#import "ContentModeViewController.h"
#import "QJViewController.h"
#import "WebViewController.h"
#import "NewWebViewController.h"
#import "FilesDownManage.h"
#import "DownViewController.h"
#import "ShowViewController.h"
#import "XLConnection.h"
#import "XLResponse.h"
#import "Reachability.h"

@interface MainViewController ()

@end

@implementation MainViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    MenuViewController * menu = [[MenuViewController alloc] initWithNibName:nil bundle:nil];
    [self setTabViewController:menu];
    self.delegate = self;
    [self showMenu];
    [FilesDownManage sharedFilesDownManageWithBasepath:@"DownLoad" TargetPathArr:[NSArray arrayWithObject:@"DownLoad"]];
    Reachability *r = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    if ([r currentReachabilityStatus] != NotReachable) {
        [self upLoadDataWithShow:NO];
        [self postClickInfo];
    }
}

- (void)postClickInfo
{
    XLConnection *connection = [[XLConnection alloc] initWithCompletionBlock:^(XLConnection *connection, XLResponse *response, NSError *error) {
        if (response) {
            if ([response isSuccessReturn]){
            NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
            [_Data setValue:@"" forKey:@"clickInfo"];
            [_Data synchronize];
            }
        }
    }];
    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
    NSString* clickInfo = [_Data objectForKey:@"clickInfo"];
    if ([clickInfo length]>0) {
        [connection postClickInfo:clickInfo];
    }
}

- (void)upLoadDataWithShow:(BOOL)isShow
{
    XLConnection *connection = [[XLConnection alloc] initWithCompletionBlock:^(XLConnection *connection, XLResponse *response, NSError *error) {
        if (response) {
            if ([response isSuccessReturn]){
            NSArray *result = [response result];
            NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
            NSMutableArray *qjList = [NSMutableArray arrayWithArray:[_Data objectForKey:@"QJData"]];
            NSMutableArray *oldT = [NSMutableArray arrayWithArray:[_Data objectForKey:@"QJTemp"]];
            NSMutableArray *new = [NSMutableArray arrayWithArray:qjList];
            NSMutableArray *newT = [NSMutableArray arrayWithArray:oldT];
            _update = [NSMutableArray array];
            for (id dic in result) {
                for (int i=0; i<[qjList count]; i++) {
                if ([[dic objectForKey:@"sid"] isEqualToString:[[qjList objectAtIndex:i] objectForKey:@"sid"]]) {
                    NSMutableDictionary *nqj = [NSMutableDictionary dictionaryWithDictionary:[qjList objectAtIndex:i]];
                    NSString *version = [nqj objectForKey:@"version"];
                    if ([version length]==0) {
                    version = @"0";}
                    if (![version isEqualToString:[dic objectForKey:@"version"]]) {
                    NSMutableDictionary *downData = [NSMutableDictionary dictionaryWithDictionary:dic];
                    [downData setValue:[nqj objectForKey:@"sortid"] forKey:@"sortid"];
                    [downData setValue:[nqj objectForKey:@"sortname"] forKey:@"sortname"];
                    [_update addObject:downData];}
                    [nqj setValue:[dic objectForKey:@"title"] forKey:@"title"];
                    [nqj setValue:[dic objectForKey:@"sharetitle"] forKey:@"sharetitle"];
                    [nqj setValue:[dic objectForKey:@"intro"] forKey:@"intro"];
                    [new removeObjectAtIndex:i];
                    [new insertObject:nqj atIndex:i];
                    break;
                    }
                }for (int i=0; i<[oldT count]; i++) {
                if ([[dic objectForKey:@"sid"] isEqualToString:[[oldT objectAtIndex:i] objectForKey:@"sid"]]) {
                    NSMutableDictionary *nqj = [NSMutableDictionary dictionaryWithDictionary:[oldT objectAtIndex:i]];
                    [nqj setValue:[dic objectForKey:@"title"] forKey:@"title"];
                    [nqj setValue:[dic objectForKey:@"sharetitle"] forKey:@"sharetitle"];
                    [nqj setValue:[dic objectForKey:@"intro"] forKey:@"intro"];
                    [newT removeObjectAtIndex:i];
                    [newT insertObject:nqj atIndex:i];
                    break;
                    }
                }
            }[_Data setObject:new forKey:@"QJData"];
            [_Data setObject:newT forKey:@"QJTemp"];
            [_Data synchronize];
            [self showUpdataNum];
            if (isShow) {
                if ([_update count] == 0) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您的所有全景都已是最新版本！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                    [alert show];
                }else{
                [self setSelectedIndex:4];
                [UIView animateWithDuration:0.1
                                 animations:^{
                                     [((MenuViewController*)self.tabViewController).bgSelectImage setFrameY:290];
                                 }];
                }
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"错误" message:[response message] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    }
    }];NSString *SIDs = @"";
    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
    NSMutableArray *allData = [NSMutableArray arrayWithArray:[_Data objectForKey:@"QJData"]];
    for (id qj in allData) {
    SIDs = [SIDs stringByAppendingFormat:@"%@|",[qj objectForKey:@"sid"]];}
    if ([SIDs length] > 0) {
    SIDs = [SIDs substringToIndex:[SIDs length]-1];
    [connection setNeedIndicator:isShow];
    [connection upDataWithSIDs:SIDs];}
}

- (void)showUpdataNum
{
    if ([self.selectedViewController isKindOfClass:[QJViewController class]]) {
        [(QJViewController*)self.selectedViewController reloadList];
    }
    [(MenuViewController*)self.tabViewController showUpdataNum];
}

- (void)showMenu
{
    QJViewController *suoyou = [[QJViewController alloc] initWithType:1];
    QJViewController *zuijin = [[QJViewController alloc] initWithType:2];
    _mulu = [[SortViewController alloc] initWithNibName:nil bundle:nil];
    UINavigationController *SortNavigation = [[UINavigationController alloc] init];
    [SortNavigation setNavigationBarHidden:YES];
    [SortNavigation pushViewController:_mulu animated:NO];
    WebViewController *xiazai = [[WebViewController alloc] initWithURL:@"http://i.svrvr.com/index.php?c=app&type=shiweiquanjingqiyebanben"];
    DownViewController*guanli = [[DownViewController alloc] initWithNibName:nil bundle:nil];
    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:@[zuijin,suoyou,SortNavigation,xiazai,guanli]];
    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
    NSArray *_menuList = [_Data objectForKey:@"menuList"];
    for (NSArray *menu in _menuList)
    {
        [viewControllers addObject:[[WebViewController alloc] initWithURL:[menu valueForKey:@"url"]]];
    }
    self.viewControllers = viewControllers;
}

- (void)TabFrameController:(TabFrameController *)tabBarController didSelectOldViewController:(UIViewController *)viewController atIndex:(NSUInteger)index
{
    if ([viewController isKindOfClass:[WebViewController class]]) {
        [(WebViewController*)viewController reLoadWeb];
    }
    else if ([viewController isKindOfClass:[UINavigationController class]]) {
        [(UINavigationController*)viewController popToRootViewControllerAnimated:YES];
    }
}

- (void)reLoadSortView
{
    if (self.selectedIndex != 2) {
        [self setSelectedIndex:2];
    }
    [(UINavigationController*)self.selectedViewController popToRootViewControllerAnimated:YES];
    [_mulu reloadData];
    [UIView animateWithDuration:0.1
                     animations:^{
                         [((MenuViewController*)self.tabViewController).bgSelectImage setFrameY:35];
                     }];
}

- (void)showSN
{
    NewWebViewController *new = [[NewWebViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:new animated:YES];
    [new setUrl:@"http://i.svrvr.com/index.php?c=member&a=invitation"];
}

- (void)showQJ:(QuanJing*)qj
{
    ShowViewController *new = [[ShowViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:new animated:YES];
    [new setQj:qj];
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm"];
    NSString* date = [formatter stringFromDate:[NSDate date]];
    NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
    NSString* str = [_Data objectForKey:@"clickInfo"];
    NSString* clickInfo = @"";
    if ([str length] > 0)
    {clickInfo = [NSString stringWithFormat:@"%@|%@,%@",str,qj.sid,date];}
    else{
    clickInfo = [NSString stringWithFormat:@"%@,%@",qj.sid,date];
    }
    [_Data setValue:clickInfo forKey:@"clickInfo"];
    [_Data synchronize];
}

- (void)showUnzipErr:(NSString*)filename
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"安装失败"
                                                    message:[NSString stringWithFormat:@"%@文件安装失败，请重新下载或与服务商联系！",filename]
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

- (void)showNewWeb:(NSString*)url
{
    NewWebViewController *new = [[NewWebViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:new animated:YES];
    [new setUrl:url];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
